package src.com.neusoft.nep.controller;

import javafx.fxml.FXML;
import javafx.scene.control.Label;
import src.com.neusoft.nep.common.AQI;
import src.com.neusoft.nep.common.FileUtils;
import src.com.neusoft.nep.entity.ProvidedData;

import java.util.*;

public class OtherDistributeController {
    @FXML
    private Label total, good, prorange, cityrange;

    private AQI aqiAnalyzer = new AQI();
    private Map<String, ProvidedData> dataMap; // 存储读取的数据

    public void initialize() {
        try {
            // 读取数据
            dataMap = FileUtils.readMapObject("AdminData.txt");

            if (dataMap == null || dataMap.isEmpty()) {
                throw new RuntimeException("数据文件为空或读取失败");
            }

            // 分析数据
            analyzeData();

            // 获取总记录数
            int totalCount = getTotalRecordCount();

            // 获取优良天数（AQI等级1和2的数量）
            Map<Integer, Integer> aqiStatistics = aqiAnalyzer.getAQIStatistics();
            int goodNumber = aqiStatistics.getOrDefault(1, 0) + aqiStatistics.getOrDefault(2, 0);

            // 计算省份和城市覆盖情况
            CoverageStats coverageStats = calculateCoverageStats();

            // 更新界面显示
            total.setText(String.valueOf(totalCount));
            good.setText(String.valueOf(goodNumber));
            prorange.setText(coverageStats.getProvinceCoverage());
            cityrange.setText(coverageStats.getCityCoverage());

        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("初始化异常: " + e.getMessage());
            setLabelsToError();
        }
    }

    // 分析数据并更新AQI统计
    private void analyzeData() {
        // 重置AQI分析器
        aqiAnalyzer.reset();

        // 分析每条数据
        for (ProvidedData data : dataMap.values()) {
            double so2 = Double.parseDouble(data.getSo2());
            double co = Double.parseDouble(data.getCo());
            double pm = Double.parseDouble(data.getPm());

            // 计算AQI等级
            int so2Level = aqiAnalyzer.getLevel(so2, "so2");
            int coLevel = aqiAnalyzer.getLevel(co, "co");
            int pmLevel = aqiAnalyzer.getLevel(pm, "pm");

            // AQI等级取各污染物等级的最大值
            int aqiLevel = Math.max(Math.max(so2Level, coLevel), pmLevel);

            // 更新统计
            aqiAnalyzer.updateAQILevel(aqiLevel);
        }
    }

    // 获取总记录数
    private int getTotalRecordCount() {
        return dataMap != null ? dataMap.size() : 0;
    }

    // 计算省份和城市覆盖统计
    private CoverageStats calculateCoverageStats() {
        Set<String> coveredProvinces = new HashSet<>();
        Set<String> coveredCities = new HashSet<>();

        for (Map.Entry<String, ProvidedData> entry : dataMap.entrySet()) {
            String key = entry.getKey();
            ProvidedData data = entry.getValue();

            // 优先从对象获取省市信息
            String province = data.getProvince();
            String city = data.getCity();

            // 如果对象中没有，则从键解析
            if ((province == null || province.isEmpty()) && (city == null || city.isEmpty())) {
                String[] parts = key.split("-");
                if (parts.length >= 1) province = parts[0];
                if (parts.length >= 2) city = parts[1];
            }

            // 添加到集合中（避免重复）
            if (province != null && !province.isEmpty()) {
                coveredProvinces.add(province);

                if (city != null && !city.isEmpty()) {
                    coveredCities.add(province + "-" + city);
                }
            }
        }

        return new CoverageStats(coveredProvinces.size(), coveredCities.size());
    }

    private void setLabelsToError() {
        total.setText("ERROR");
        good.setText("ERROR");
        prorange.setText("ERROR");
        cityrange.setText("ERROR");
    }

    // 内部类：用于存储覆盖率统计结果
    private static class CoverageStats {
        private static final int TOTAL_PROVINCES = 34; // 中国省份总数
        private static final int TOTAL_CITIES = 105;   // 假设的城市总数

        private final int provinceCount;
        private final int cityCount;

        public CoverageStats(int provinceCount, int cityCount) {
            this.provinceCount = provinceCount;
            this.cityCount = cityCount;
        }

        public String getProvinceCoverage() {
            return String.format("%d/%d (%.1f%%)",
                    provinceCount,
                    TOTAL_PROVINCES,
                    (provinceCount * 100.0 / TOTAL_PROVINCES));
        }

        public String getCityCoverage() {
            return String.format("%d/%d (%.1f%%)",
                    cityCount,
                    TOTAL_CITIES,
                    (cityCount * 100.0 / TOTAL_CITIES));
        }
    }
}